package com.mlnx.bluwifi.broadcast;

import com.alibaba.fastjson.JSONArray;
import com.mlnx.bluwifi.manager.ConDeviceManage;
import com.mlnx.bluwifi.pojo.dto.LanyaSpo;
import com.mlnx.bluwifi.service.WifiBluService;
import com.mlnx.common.utils.MyLog;
import com.mlnx.device.service.LanyaDeviceService;

import org.apache.commons.lang3.StringUtils;
import org.shan.mq.broker.broadcast.ByteBufMsgBrocadCast;
import org.shan.mq.session.core.Session;
import org.shan.mq.session.core.SessionManager;

import java.nio.charset.Charset;
import java.util.List;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;

/**
 * Created by amanda.shan on 2019/11/18.
 */
public class BluDeviceBroadCast extends ByteBufMsgBrocadCast {

    MyLog log = MyLog.getLog(getClass());

    private LanyaDeviceService lanyaDeviceService;

    private WifiBluService wifiBluService;


    public BluDeviceBroadCast(SessionManager sessionManager, LanyaDeviceService lanyaDeviceService,
                              WifiBluService wifiBluService) {
        super(sessionManager);
        this.lanyaDeviceService = lanyaDeviceService;
        this.wifiBluService = wifiBluService;

    }

    @Override
    public void broadCastMsg(Channel channel, String topic, int packetId, ByteBuf payload) {

        byte[] bytes = new byte[payload.readableBytes()];
        payload.readBytes(bytes);
        String contant = new String(bytes, Charset.forName("UTF-8"));

        Session session = sessionManager.getSession(channel);

        String blueMac = session.getClientId();
        log.debug("{}:{}", blueMac, contant);

        blueMac = blueMac.subSequence(0, blueMac.length() - 2).toString();
        List<LanyaSpo> lanyaSpos = JSONArray.parseArray(contant, LanyaSpo.class);
        for (LanyaSpo lanyaSpo : lanyaSpos) {

            String spoMac = lanyaSpo.getBdaddrs().get(0).getBdaddr();
            String type = lanyaSpo.getBdaddrs().get(0).getBdaddrType();

            String ipByBluMac = lanyaDeviceService.getIpByBluMac(blueMac);
            if (StringUtils.isEmpty(ipByBluMac)) {
                log.error("{} 蓝牙ap ip地址未设置", blueMac);
            } else {
                ConDeviceManage.getInstance().connect(spoMac, blueMac, ipByBluMac, type);
            }
        }
    }
}
